<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.categoryName" placeholder="分类名" style="width: 200px;"
       class="filter-item" @keyup.enter.native="handleFilter" />
       <el-input v-model="listQuery.brandName" placeholder="品牌名" style="width: 200px;"
       class="filter-item" @keyup.enter.native="handleFilter" />
       <el-input v-model="listQuery.productName" placeholder="商品名" style="width: 200px;"
       class="filter-item" @keyup.enter.native="handleFilter" />
       <el-input v-model="listQuery.productColor" placeholder="商品颜色" style="width: 200px;"
       class="filter-item" @keyup.enter.native="handleFilter" />
       <el-input v-model="listQuery.productMaterial" placeholder="商品材质" style="width: 200px;"
       class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>

    <!--表格内容-->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="productId" sortable="custom" align="center" width="80" :class-name="getSortClass('productId')">
        <template slot-scope="{row}">
          <span>{{ row.productId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类名" prop="categoryName"  align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.categoryName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品牌名" prop="brandName"  align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.brandName }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="LOGO" prop="brandImage"  align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.brandImage }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="商品名" prop="productName"  align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.productName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品单价" prop="unitPrice"  align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.unitPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品图片" align="center" width="100">
      <template slot-scope="{row}">
        <img v-if="row.productImage" :src="row.productImage" style="width: 50px; height: 50px;" />
        <span v-else>无图片</span>
      </template>
    </el-table-column>
      <el-table-column label="商品颜色" prop="productColor" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.productColor }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品尺寸" prop="productSize"  align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.productSize }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品材质" prop="productMaterial"  align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.productMaterial }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品重量" prop="weight"  align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.weight }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存" prop="stock"  align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.stock }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销量" prop="sales" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.sales }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上架时间" prop="launchTime" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.launchTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="折扣" prop="discountRate" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.discountRate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠活动名称" prop="discountName" align="center" width="150">
        <template slot-scope="{row}">
          <span>{{ row.discountName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row, $index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">{{ $t('table.edit') }}</el-button>
          <el-button v-if="row.status != 'deleted'" size="mini" type="danger" @click="handleDelete(row, $index)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 修改的表单 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left: 50px;">
        <el-form-item label="商品ID">
          <el-input v-model="temp.productId" :autosize="{ minRows: 2, maxRows: 4}" 
           retype="text" readonly=""/>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="temp.categoryId" placeholder="请选择分类" clearable class="filter-item" style="width: 130px">
            <el-option v-for="item in categoryAllList" :key="item.categoryId" :label="item.categoryName+'('+item.categoryId+')'" :value="item.categoryId" />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="temp.brandId" placeholder="请选择品牌" clearable class="filter-item" style="width: 130px">
            <el-option v-for="item in brandAllList" :key="item.brandId" :label="item.brandName+'('+item.brandId+')'" :value="item.brandId" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名">
          <el-input v-model="temp.productName" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="请输入商品名" />
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="temp.unitPrice" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="请输入商品单价" />
        </el-form-item>
        <el-upload
        class="avatar-uploader"
        action="/api/shop/product/upload"
        :headers="{'productId': temp.productId}" 
        :show-file-list="false"
        :on-success="handleUploadSuccess"
        :before-upload="beforeUpload"
         >
          <img v-if="temp.productImage" :src="temp.productImage" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-form-item label="颜色">
          <el-input v-model="temp.productColor" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="请输入商品颜色" />
        </el-form-item>
        <el-form-item label="尺寸">
          <el-input v-model="temp.productSize" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="请输入商品尺寸" />
        </el-form-item>
        <el-form-item label="材质">
          <el-input v-model="temp.productMaterial" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="请输入商品材质" />
        </el-form-item>
        <el-form-item label="重量">
          <el-input v-model="temp.weight" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="请输入商品重量" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="temp.stock" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="请输入商品库存" />
        </el-form-item>
        <el-form-item label="销量">
          <el-input v-model="temp.sales" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="请输入商品销量" />
        </el-form-item>
        <el-form-item label="上架时间">
          <el-input v-model="temp.launchTime" :autosize="{ minRows: 2, maxRows: 4}" type="date" placeholder="请输入上架时间" />
        </el-form-item>
        <el-form-item label="折扣">
          <el-select v-model="temp.discountId" placeholder="请选择折扣类型" clearable class="filter-item" style="width: 130px">
            <el-option v-for="item in discountAllList" :key="item.discountId" :label="item.discountName+'('+item.discountId+')'" :value="item.discountId" />
          </el-select>
        </el-form-item>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { findPage, addProduct, updateProduct, deleteProduct, findAllList } from '@/api/product'
import { findAllCategoryList} from '@/api/category'
import { findBrandAllList} from '@/api/brand'
import { findDiscountAllList} from '@/api/discount'
import waves from '@/directive/waves' // waves directive
import moment from 'moment'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { get } from 'sortablejs'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      tableKey: 0,
      list: null, // 表格集合数据
      total: 0, // 总条数
      listLoading: true,
      listQuery: { // 查询的筛选条件
        page: 1,
        limit: 20,
        categoryName: undefined,
        brandName: undefined,
        productName: undefined,
        productColor: undefined,
        productMaterial: undefined,
      },
      categoryAllList:'',
      brandAllList:'',
      discountAllList:'',
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      showReviewer: false,
      temp: { // 修改信息
        productId: undefined,
        categoryId:"",
        categoryName:'',
        brandId: "",
        brandName: "",
        // brandImage: "",
        productName: "",
        unitPrice: "",
        productImage: "",
        productColor: "",
        productSize: "",
        productMaterial: "",
        weight: "",
        stock: "",
        sales: "",
        launchTime: "",
        discountId: "",
        discountRate: "",
        discountName: "",
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        productName: [{ required: true, message: '商品名不能为空', trigger: 'blur' }],
        unitPrice: [{ required: true, message: '单价不能为空', trigger: 'blur' }],
      },
      downloadLoading: false
    }
  },
  created() { // 未渲染之前 data加载之后
    this.getList()
    this.getcategoryList()
    this.getBrandList()
    this.getDiscountList()
  },
  methods: {
    async getList() {
      this.listLoading = true;
      findPage(this.listQuery).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        setTimeout(() => {
          this.listLoading = false;
        })
      })
    },
    getcategoryList(){
      findAllCategoryList().then(response=>{
        this.categoryAllList=response.data.list
      })
    },
    getBrandList(){
      findBrandAllList().then(response=>{
        this.brandAllList=response.data.list
      })
    },
    getDiscountList(){
      findDiscountAllList().then(response=>{
        this.discountAllList=response.data.list
      })
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === 'id') {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id';
      } else {
        this.listQuery.sort = '-id';
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        productId: undefined,
        categoryId: "",
        categoryName:'',
        brandId: undefined,
        brandName: "",
        // brandImage: "",
        productName: "",
        unitPrice: "",
        productImage: "",
        productColor: "",
        productSize: "",
        productMaterial: "",
        weight: "",
        stock: "",
        sales: "",
        launchTime: "",
        discountId: "",
        discountRate: "",
        discountName: "",
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
        formatDate() {
        // 确保 birthDate 是一个 Date 对象
        if (typeof this.temp.launchTime === 'string') {
        this.temp.launchTime = new Date(this.temp.launchTime); // 转换为 Date 对象
        }

        // 确保 birthDate 是有效的 Date 对象
        if (this.temp.launchTime instanceof Date && !isNaN(this.temp.launchTime)) {
        this.temp.launchTime = this.temp.launchTime.toISOString().split('T')[0]; // 转换为 yyyy-MM-dd 格式
        } else {
        console.error('Invalid date format'); // 处理无效日期的情况
        }
        },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        this.formatDate()
        console.log(this.temp)
        if (valid) {
          this.temp.launchTime=moment(String(this.temp.launchTime)).format('YYYY-MM-DD')
         
          addProduct(this.temp).then(response => {
            this.dialogFormVisible = false;
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            });
            this.getList();
          });
        }
        
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.dialogStatus = 'update';
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        this.formatDate()
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          updateProduct(tempData).then(() => {
            this.dialogFormVisible = false;
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            });
            this.getList();
          });
        }
      });
    },
    handleDelete(row, index) {
      deleteProduct(row.productId).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        });
        this.getList();
      });
    },
    handleFetchPv(pv) {
      // Implement if needed
    },
    handleUploadSuccess(response, file) {
      if (response && response.url) {
        this.temp.productImage = response.url; // 更新 brandImage 属性为服务器返回的图片 URL
      } else {
        this.$message.error('上传失败，请稍后再试');
      }
    },
    beforeUpload(file) {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGorPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }

      return isJPGorPNG && isLt2M;
    },
    getSortClass(key) {
    const sort = this.listQuery.sort;
    if (sort === `+${key}`) {
      return 'ascending';
    } else if (sort === `-${key}`) {
      return 'descending';
    }
    return '';
  }
  }
}
</script>

</script>

<style scoped>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}

.avatar-uploader .el-upload:hover {
border-color: #409eff;
}

.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}

.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>